package com.ccy.springboot149.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ccy.springboot149.dao.TokenDao;
import com.ccy.springboot149.entity.TokenEntity;
import com.ccy.springboot149.service.TokenService;
import com.ccy.springboot149.utils.CommonUtil;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.Callable;

/**
 * @Author : CaiYang
 * @Date : 2025-07-02 23:25
 * @Description :
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {

    @Override
    public String generateToken(Integer userid, String username, String tableName, String role) {
        TokenEntity tokenEntity = this.selectOne(new EntityWrapper<TokenEntity>().eq("userid",userid).eq("role",role));
        String token = CommonUtil.getRandomString(32);
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.HOUR_OF_DAY,1);
        if(tokenEntity != null) {
            tokenEntity.setToken(token);
            tokenEntity.setExpiratedtime(cal.getTime());
            this.updateById(tokenEntity);
        } else {
            this.insert(new TokenEntity(userid,username,tableName,role,token,cal.getTime()));
        }
        return token;
    }
}
